package com.example.demo.framework.filters.tracer;

import com.example.demo.utils.HttpUtils;
import com.example.demo.utils.SpringBeanUtils;
import lombok.Data;
import org.apache.logging.log4j.util.Strings;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.UUID;

/**
 * @Auther: miaoguoxin
 * @Date: 2020/3/20 13:44
 * @Description:
 */
@Data
public class TraceInfo {
    private TraceInfo previous;
    private TraceInfo next;
    private String traceId;
    private String serviceId;
    private String uri;
    private String hostAddr;

    public TraceInfo() {

    }

    public void buildPrevious(HttpServletRequest request){
        String parentId = request.getHeader(TraceConst.TRACE_ID);
        if (Strings.isNotBlank(parentId)){
            this.previous = new TraceInfo();
            String remoteIP = HttpUtils.getRemoteIp(request);
            previous.setTraceId(parentId);
            previous.setServiceId(request.getHeader(TraceConst.SERVICE_ID));
            previous.setUri(request.getHeader(TraceConst.REQUEST_URI));
            previous.setHostAddr(String.format("%s:%d",remoteIP,request.getRemotePort()));
        }
    }

    public void buildCurrent(HttpServletRequest request) throws UnknownHostException {
        this.traceId = UUID.randomUUID().toString();
        this.serviceId = SpringBeanUtils.getProperty("spring.application.name");
        this.uri = request.getServletPath();
        this.setHostAddr(String.format("%s:%s",InetAddress.getLocalHost().getHostAddress(),SpringBeanUtils.getProperty("server.port")));
    }


    public void buildNext(String servicePath, String url) throws MalformedURLException {
        this.next = new TraceInfo();
        URL pathUrl = new URL(servicePath);
        URL requestUrl = new URL(url);
        this.next.setTraceId(this.traceId);
        this.next.setServiceId(pathUrl.getHost());
        this.next.setHostAddr(String.format("%s:%d",requestUrl.getHost(),requestUrl.getPort()));
        this.next.setUri(requestUrl.getPath());
    }



    @Override
    public String toString() {
        return "TraceInfo{" +
                "previous=" + previous +
                ", next=" + next +
                ", traceId='" + traceId + '\'' +
                ", serviceId='" + serviceId + '\'' +
                ", uri='" + uri + '\'' +
                ", hostAddr='" + hostAddr + '\'' +
                '}';
    }
}
